import {WeaTools} from "ecCom";
import * as types from "../constants/ActionTypes";
import * as urls from "../constants/ServerUrls";
import SearchFavourite from "../util/SearchFavourite";
import {handleDragNodeData, getNodeData} from "../util/TreeUtil";

const {callApi} = WeaTools;

/**
 * 加载目录树
 * @param parentId
 * @returns {function(*)}
 */
export const loadTree = parentId => {
    return dispatch => {
        let treeurl = urls.LOAD_TREE_URL;
        callApi(treeurl, "POST", {parentId}).then(resdata => {
            let msg = resdata.msg;
            let success = resdata.success;
            if (success == "1") {
                let data = resdata.data;
                dispatch(setTreeData(data, parentId, success, msg));
            }
        });
    }
}


/**
 * 加载一个节点的数据，并展开这个节点
 * @param parentId
 * @returns {function(*)}
 */
export const loadAndExpand = parentId => {
    return dispatch => {
        let treeurl = urls.LOAD_TREE_URL;
        callApi(treeurl, "POST", {parentId}).then(resdata => {
            let msg = resdata.msg;
            let success = resdata.success;
            if (success == "1") {
                let data = resdata.data;
                dispatch(setTreeData(data, parentId, success, msg));
                dispatch(expandTreeNode([parentId], true));
            }
        });
    }
}

/**
 * 节点选中
 * @param selectedKey
 * @returns {function(*): *}
 */
export const selectTreeNode = selectedKey => {
    return {
        type: types.FAVOURITE_SELECT_DIR,
        selectedKey
    };
}

/**
 * 节点展现记录
 * @param expandedKeyArr
 * @param expanded
 * @returns {{type, expandedKey: *, expanded: *}}
 */
export const expandTreeNode = (expandedKeyArr, expanded) => {
    return {
        type: types.FAVOURITE_EXPAND_DIR,
        expandedKeyArr,
        expanded
    }
}

/**
 * 添加树节点
 * @param selectedKey
 * @returns {{type, selectedKey: *}}
 */
export const addTreeNode = selectedKey => {
    return {
        type: types.FAVOURITE_ADD_DIR,
        selectedKey
    };
}

/**
 * 编辑节点
 * @param operatingKey
 */
export const editTreeNode = (nodeKey) => {
    return {
        type: types.FAVOURITE_EDIT_DIR,
        nodeKey
    }
}

/**
 * 保存新增的树节点
 * @param params
 */
export const saveAddTreeNode = params => {
    let favurl = urls.ADD_FAVOURITE_DIR;
    let {parentid} = params;
    return dispatch => {
        callApi(favurl, "POST", {...params}).then(resdata => {
            let success = resdata.success;
            let msg = "";
            if (success == "0") {
                msg = resdata.msg;
            }

            //错误处理
            dispatch({
                type: types.MYFAV_RESULT_SET,
                success,
                msg
            });
            dispatch(loadTree(parentid));  //刷新父节点下的所有节点
        });
    }
}

/**
 * 保存编辑的树节点
 * @param params
 * @returns {function(*)}
 */
export const saveEditTreeNode = params => {
    let favurl = urls.EDIT_FAVOURITE_DIR;
    let {parentid, favname, favid} = params;
    return dispatch => {
        callApi(favurl, "POST", {...params}).then(resdata => {
            let success = resdata.success;
            let msg = "";

            let isinput = false;
            if (success == "0") {
                msg = resdata.msg;
                isinput = true;
            }

            //错误处理
            dispatch({
                type: types.MYFAV_RESULT_SET,
                success,
                msg
            });

            dispatch(updateTreeNodeData(favid, {favname, isinput}));
            dispatch(setClickExpanded(true));
        });
    }
}

export const deleteTreeNode = favid => {
    let favurl = urls.DELETE_FAVOURITE_DIR;
    return dispatch => {
        callApi(favurl, "POST", {favid}).then(resdata => {
            let success = resdata.success;
            let msg = "";
            if (success == "0") {
                msg = resdata.msg;

                //错误处理
                dispatch({
                    type: types.MYFAV_RESULT_SET,
                    success,
                    msg
                });
            } else {
                let nodeId = "-1";
                dispatch(selectTreeNode(nodeId));   //默认选中“我的收藏”

                /**
                 * 选中树节点后，刷新收藏的列表
                 */
                let isinit = true;
                let isreload = false;
                SearchFavourite.setConditions({dirId: nodeId});
                let searchFavourite = new SearchFavourite(dispatch);
                searchFavourite.load({isinit, isreload});

                /**
                 * 刷新父节点
                 */
                let {parent} = resdata;
                let parentId = parent.favid;  //父节点id
                dispatch(loadTree(parentId));  //重新加载父节点下的所有子节点
                dispatch(updateTreeNodeData(parentId, parent));
            }
        });
    }
}

export const handleDragNode = (dragKey, dropKey, dropPos, dropToGap) => {
    return (dispatch, getState) => {
        let {treeData} = getState().favouritedir;
        let ndata = jQuery.extend(true, [], treeData);   //深度copy数据
        let dragInfo = {dragKey, dropKey, dropPos, dropToGap};
        let handleResult = handleDragNodeData(ndata, dragInfo);
        let {list, node, dragParentId, dropParentId, islast} = handleResult;
        ({treeData} = handleResult);
        //树数据更新
        dispatch({
            treeData,
            type: types.FAVOURITE_DRAG_NODE
        });

        //展开节点
        dispatch({
            type: types.FAVOURITE_EXPAND_DIR,
            expandedKeyArr: [dropKey],
            expanded: true
        });

        /**
         * 异步请求，保存数据到服务器端
         */
        list = jQuery.extend(true, [], list);   //深度copy数据
        list = list.map(function (item, index) {
            let {favid, parentid} = item;
            return {favid, parentid, index};
        });

        list = JSON.stringify(list);
        node = JSON.stringify(node);
        let saveurl = urls.SAVE_FAVOURITE_DIR;
        callApi(saveurl, "POST", {list, node, islast, dragParentId}).then(resdata => {
            let success = resdata.success;
            let msg = "";
            if (success == "0") {
                msg = resdata.msg;
                //错误处理
                dispatch({
                    type: types.MYFAV_RESULT_SET,
                    success,
                    msg
                });
            } else {
                /**
                 * 刷新拖动节点的父节点，因为拖动后，可能就没有子节点了
                 */
                let {parent} = resdata;
                let parentId = parent.favid;  //父节点id
                dispatch(updateTreeNodeData(parentId, parent));   //更新父节点的信息
            }
        });
    }
}

/**
 * 更新树某一节点的信息
 * @param nodeKey
 * @param params
 * @returns {{type, nodeKey: *, params: *}}
 */
export const updateTreeNodeData = (nodeKey, params) => {
    return {
        type: types.FAVOURITE_UPDATE_NODE_DATA,
        nodeKey,
        params
    }
}

/**
 * 根目录（全部目录）鼠标移入、移出状态设置
 * @param isover
 * @returns {{type, isover: *}}
 */
export const setRootOver = isover => {
    return {
        type: types.FAVOURITE_ROOT_OVER,
        isover
    }
}

/**
 * 根目录（全部目录）选中状态设置
 * @param isselected
 * @returns {{type, isselected: *}}
 */
export const setRootClick = isselected => {
    return {
        type: types.FAVOURITE_ROOT_SELECTED,
        isselected
    }
}

/**
 * 设置，是否点击时，展开节点
 * @param expanded
 * @returns {{type, expanded: *}}
 */
export const setClickExpanded = expanded => {
    return {
        type: types.FAVOURITE_CLICK_EXPANDED,
        expanded
    }
}

/**
 * 鼠标移动到节点上，显示编辑、删除操作按钮
 * @param nodeKey
 * @returns {{type, nodeKey: *}}
 */
export const toggleNodeOperation = (nodeKey, isover) => {
    return {
        type: types.FAVOURITE_TOGGLE_OPERATION,
        nodeKey,
        isover
    }
}

/**
 * 获取节点信息
 * @param nodeKey
 * @returns {function(*, *)}
 */
export const getNodeInfo = (nodeKey) => {
    return (dispatch, getState) => {
        let {treeData} = getState().favouritedir;
        let ndata = getNodeData(treeData, nodeKey);
        return ndata;
    }
}

function setTreeData(data, parentId) {
    return {
        type: types.FAVOURITE_LOAD_TREE,
        treeData: data,
        parentId
    };
}